package com.diamond.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import com.diamond.bo.QueryUserBO;
import com.diamond.bo.ReturnBO;
import com.diamond.bo.SalesBO;
import com.diamond.bo.UserBO;
import com.diamond.entity.User;
import com.diamond.po.UserPO;
import com.diamond.service.IUserService;
import com.diamond.util.MD5;
import com.diamond.util.StringUtil;

/**
 * @author JSmart Tools
 */
@SuppressWarnings("unchecked")
public class UserService extends Service<UserPO> implements IUserService {

	public void addOrUpdateUser(UserPO userPo)throws Exception {
		User user = new User();
		PropertyUtils.copyProperties(user, userPo);
		super.genericDAO.saveOrUpdate(user);
	}

	public ReturnBO<UserBO> queryUser(QueryUserBO queryUserBo) throws Exception {
		ReturnBO<UserBO> returnBo = new ReturnBO<UserBO>();
		StringBuilder queryUserSql = new StringBuilder("select distinct * from user where 1=1 and user.del_status='0'");
		StringBuilder querySizeSql = new StringBuilder("select distinct * from user where 1=1 and user.del_status='0'");
		if (null != queryUserBo.getUserName()&& !"".equals(queryUserBo.getUserName())) {
			queryUserSql.append(" and user.user_name like '%").append(queryUserBo.getUserName()).append("%'");
			querySizeSql.append(" and user.user_name like '%").append(queryUserBo.getUserName()).append("%'");
		}
		if (null != queryUserBo.getCmpName()&& !"".equals(queryUserBo.getCmpName())) {
			queryUserSql.append(" and user.cmp_name like '%").append(queryUserBo.getCmpName()).append("%'");
			querySizeSql.append(" and user.cmp_name like '%").append(queryUserBo.getCmpName()).append("%'");
		}
		if (null != queryUserBo.getRegisterDateFrom()&& !"".equals(queryUserBo.getRegisterDateFrom())
				&& null != queryUserBo.getRegisterDateTo()&& !"".equals(queryUserBo.getRegisterDateTo())) {
			queryUserSql.append(" and user.register_date between '").append(queryUserBo.getRegisterDateFrom()).append("' and '").append(queryUserBo.getRegisterDateTo()).append("'");
			querySizeSql.append(" and user.register_date between '").append(queryUserBo.getRegisterDateFrom()).append("' and '").append(queryUserBo.getRegisterDateTo()).append("'");
		}
		if (null != queryUserBo.getContact()&& !"".equals(queryUserBo.getContact())) {
			queryUserSql.append(" and user.contact like '%").append(queryUserBo.getContact()).append("%'");
			querySizeSql.append(" and user.contact like '%").append(queryUserBo.getContact()).append("%'");
		}
		queryUserSql.append(" order by user.register_date desc").append(" limit ").append(queryUserBo.getStart()).append(", ").append(queryUserBo.getPageSize());
		List<UserBO> userBolist = super.genericDAO.findBySqlToObj(queryUserSql.toString(), UserBO.class);
		List userBoSizelist = super.genericDAO.findBySqlToObj(querySizeSql.toString(), null);
		returnBo.setTotalSize(userBoSizelist.size());
		returnBo.setReturnBolist(userBolist);
		returnBo.setPageSize(queryUserBo.getPageSize());
		returnBo.setStart(queryUserBo.getStart());
		return returnBo;
	}

	public UserBO findUserByUserId(String userId)throws Exception {
		StringBuilder sql = new StringBuilder("select * from user where 1=1 and user.del_status=0 and user.user_id=").append(userId);
		List<UserBO> userBolist = super.genericDAO.findBySqlToObj(sql.toString(), UserBO.class);
		if (userBolist.size() > 0) {
			return userBolist.get(0);
		} else {
			return null;
		}
	}

	public Boolean deleteUser(String[] userIds) throws Exception {
		Boolean result = false;
		StringBuilder delSql = new StringBuilder("update user set user.del_status=1 where user.user_id in (");
		for (int i=0; i<userIds.length; i++) {
			if (i < userIds.length - 1) {
				delSql.append(userIds[i]).append(",");
			} else {
				delSql.append(userIds[i]).append(")");
			}
		}
		Integer i = super.genericDAO.updateBySql(delSql.toString());
		if (i > 0) {
			result = true;
		}
		return result;
	}

	public Boolean checkUserName(String userName) throws Exception {
		Boolean result = false;
		String sql = "select * from user where 1=1 and user.del_status = 0 and user.user_name='" +userName+ "'";
		List<UserBO> list = super.genericDAO.findBySqlToObj(sql, UserBO.class);
		if (list.size() == 0) {
			result = true;
		}
		return result;
	}

	public List<UserBO> queryUserByUserType(String[] userTypes) throws Exception {
		StringBuilder sql = new StringBuilder("SELECT * from user where user.del_status = 0 and user.user_type in (");
		for (int i = 0; i<userTypes.length; i++) {
			if (i < userTypes.length - 1) {
				sql.append("'").append(userTypes[i]).append("'").append(",");
			} else {
				sql.append("'").append(userTypes[i]).append("'").append(")");	
			}
		}
		return super.genericDAO.findBySqlToObj(sql.toString(), UserBO.class);
	}

	public List<UserBO> backLogin(UserBO userBo) throws Exception {
		String sql = "select * from user where user.del_status=0 and user.user_type in ('A','E') and user.user_name='" + userBo.getUserName() + "' and user.password='" + userBo.getPassword()+"'";
		List<UserBO> list = super.genericDAO.findBySqlToObj(sql, UserBO.class);
		return list;
	}

	@Override
	public User login(UserBO userBo) {
		if(userBo==null)return null;
		try {
		String HQL="from User as o where o.userName=? and o.password=? and o.delStatus='0' ";
		if(!StringUtil.isEmpty(userBo.getPassword())){
			String pass = MD5.encode(userBo.getPassword());
			Object[] paras = new Object[]{userBo.getUserName(),pass};
			List list = genericDAO.find(HQL, paras);
			if(list!=null&&list.size()>0){
				User user = (User) list.get(0);
				if("D".equals(user.getUserType())&&user.getParentDealerId()!=null){
					user= (User) genericDAO.findById(user.getParentDealerId());
				}
				return user;
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public User loginCenter(UserBO userBo) {
		if(userBo==null)return null;
		String HQL="from User as o where o.userName=? and o.password=? and (userType='C' or userType='B') and o.delStatus='0' ";
		if(!StringUtil.isEmpty(userBo.getPassword())){
			String pass = MD5.encode(userBo.getPassword());
			Object[] paras = new Object[]{userBo.getUserName(),pass};
			List list = genericDAO.find(HQL, paras);
			if(list!=null&&list.size()>0)return (User) list.get(0);
		}
		return null;
	}

	@Override
	public void updateSonPass(Long userId, String pass) {
		if(userId==null||pass==null)return;
		String HQL="update User set password='"+MD5.encode(pass)+"' where parentDealerId="+userId;
		genericDAO.bulkUpdate(HQL);
	}

	public List getSales(Long parentUserId, SalesBO searchBO) {
		String HQL="from User where parentAgentId="+parentUserId;
		List list = genericDAO.findByHQL(HQL);
		if(list==null&&list.size()==0)return null;
		String startDate=null;
		String endDate=null;
		String cmpName=null;
		if(searchBO!=null){
			startDate = searchBO.getStartDate();
			endDate = searchBO.getEndDate();
			cmpName = searchBO.getCmpName();
		}
		List retunList = new ArrayList();
		for(int i=0;i<list.size();i++){
			User user = (User) list.get(i);
			if(cmpName!=null&&!"".equals(cmpName)&&!cmpName.equals(user.getCmpName()))continue;
			SalesBO salesBO = new SalesBO();
			salesBO.setCmpName(user.getCmpName());
			salesBO.setCmpTel(user.getCmpTel());
			salesBO.setContact(user.getContact());
			salesBO.setContactTel(user.getCmpTel());
			salesBO.setStartDate(startDate);
			salesBO.setEndDate(endDate);
			HQL="select sum(mid_total) from clientorder where del_state='0' and user_id="+user.getUserId();
			if(startDate!=null&&!"".equals(startDate))HQL+=" and order_date>='"+startDate+"'";
			if(endDate!=null&&!"".equals(endDate))HQL+=" and order_date<='"+endDate+"'";
			
			List sums=genericDAO.findByNHQL(HQL);
			if(sums!=null&&sums.size()>0&&!StringUtil.isEmpty(sums.get(0))){
				salesBO.setTotal(StringUtil.doubleFmt((Double) sums.get(0)));
			} else {
				salesBO.setTotal(0d);
			}
			retunList.add(salesBO);
		}
		return retunList;
	}

	@Override
	public Boolean updateBackUserPW(Long userId, String oldPassword,
			String newPassword) throws Exception {
		String sql = "update user set password='"+newPassword+"' where user_id="+userId+" and password='"+oldPassword+"' and user_type in ('A', 'E')";
		super.genericDAO.updateBySql(sql);
		return true;
	}

	@Override
	public List<UserBO> searchSubUser(Long userId) throws Exception {
		String sql = "select * from user where parent_dealer_id=" + userId;
		List<UserBO> subUserNamelist = super.genericDAO.findBySqlToObj(sql, UserBO.class);
		return subUserNamelist;
	}

	@Override
	public void updateSonPassByUserId(Long subUserId, String surepass) {
		if(subUserId==null||surepass==null)return;
		String HQL="update User set password='"+MD5.encode(surepass)+"' where userId="+subUserId;
		genericDAO.bulkUpdate(HQL);		
	}
	
}
